import logging
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from django.utils.translation import gettext_lazy as _
from weixin import views as weixin_api
from teacher.models import TeacherModel
from teacher.serializers import TeacherSerl

logger = logging.getLogger("log")


class TeacherTokenSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        username = attrs.get("username")
        password = attrs.get("password")
        request = self.context["request"]
        condition = request.data["condition"]
        if condition == "jscode":
            jscode = request.data["jscode"]
            req_res = weixin_api.get_openid(jscode)
            if req_res.get("code") != 0:
                return {"code": 500, "msg": "获取access_token失败"}
            req_data = req_res["data"]
            print("req_data", req_data)
            openid = req_data["openid"]
            try:
                teacher = TeacherModel.objects.get(openid=openid)
                refresh = self.get_token(teacher)
                token = str(refresh.access_token)
                return_data = {"token": token, "teacher": TeacherSerl(teacher).data}
                return {"code": 0, "msg": "OK", "data": return_data}
            except TeacherModel.DoesNotExist:
                return_data = {"openid": openid}
                return {"code": 404, "msg": "非法用户", "data": return_data}
        elif condition == "phonecode":
            phone_code = request.data["phonecode"]
            openid = request.data["openid"]
            phone_request = weixin_api.get_weixin_phone(phone_code)
            if phone_request.get("code") != 0:
                return {"code": 500, "msg": "获取手机号码失败"}
            phone_request_data = phone_request["data"]
            phone = phone_request_data["phone"]
            try:
                teacher = TeacherModel.objects.get(phone=phone)
                teacher.openid = openid
                teacher.save()
                refresh = self.get_token(teacher)
                token = str(refresh.access_token)
                return_data = {"token": token, "teacher": TeacherSerl(teacher).data}
                return {"code": 0, "msg": "OK", "data": return_data}
            except TeacherModel.DoesNotExist:
                return_data = {"openid": openid,"phone": phone}
                return {"code": 404, "msg": "非法用户", "data": return_data}
        elif condition == "openid":
            openid = request.data["openid"]
            try:
                teacher = TeacherModel.objects.get(openid=openid)
                refresh = self.get_token(teacher)
                token = str(refresh.access_token)
                return_data = {"token": token, "teacher": TeacherSerl(teacher).data}
                return {"code": 0, "msg": "OK", "data": return_data}
            except TeacherModel.DoesNotExist:
                return_data = {"phone": phone}
                return {"code": 404, "msg": "非法用户", "data": return_data}


class TeacherTokenView(TokenObtainPairView):
    serializer_class = TeacherTokenSerializer


class TeacherJWT(JWTAuthentication):
    def get_user(self, validated_token):
        # print("validated_token", validated_token)
        # print("user_id", validated_token["user_id"])
        try:
            user_id = validated_token["user_id"]
        except KeyError:
            raise InvalidToken(_("Token contained no recognizable user identification"))
        try:
            teacher = TeacherModel.objects.get(**{"id": user_id})
        except TeacherModel.DoesNotExist:
            raise AuthenticationFailed(_("User not found"), code="user_not_found")
        return teacher
